<?php
namespace app\admin\controller;

use app\admin\model\Article as ArticleModel;

use think\Controller;
use think\Db;

class Index extends Controller
{
    //初始化方法
    public function _initialize()
    {
        $renderData = [
            "id" => session('id'), //登入状态
            "username" => session('username'),
        ];

        $this->assign($renderData);
    }

    //渲染首页
    public function index()
    {
        return $this->fetch();
    }

    //渲染添加文章
    public function add_article()
    {
        return $this->fetch();
    }

    //渲染修改文章
    public function update_article()
    {
        $id = $_GET["id"];
        $targetArticle = ArticleModel::get($id)->toArray();
        $this->assign($targetArticle);
        return $this->fetch();
    }

        //渲染文章页面
        public function articles()
        {
    
            $articles = ArticleModel::all([
                "u_id" => session("id"),
                "status" => "1"
            ]);
            foreach($articles as  $key => $article) {
                $articles[$key] = $article->toArray();
            }
    
            $this->assign('articles', $articles);
    
            return $this->fetch();
        }

    //添加文章
    public function addArticle()
    {
        $newArticle = new ArticleModel([
            "title" => $_POST["title"],
            "content" => $_POST["content"],
            "u_id" => session("id"),
            "create_time" => time(),
            "update_time" => time(),
            "status" => '1'
        ]);
        
        $result = $newArticle->save();
        
        //插入结果
        if($result == 1) {  
            $this->success("发布成功", "admin/index/articles");
        }else {
            $this->success("发布失败", "admin/index/add_article"); 
        }
    }   

    //删除文章
    public function deleteArticle()
    {
        $id = $_GET["id"];
        $targetArticle = ArticleModel::get($id);
        $targetArticle->status = "0";
        $result = $targetArticle->save();
        //删除结果
        if($result == 1) {  
            $this->success("删除成功", "admin/index/articles");
        }else {
            $this->success("删除失败"); 
        }
    } 

    //更新文章
    public function updateArticle()
    {
        $title = $_POST["title"];
        $content = $_POST["content"];
        $id = $_GET["id"];
        $newArticle = ArticleModel::get($id);
        $newArticle->title = $title;
        $newArticle->content = $content;
        $result = $newArticle->save();
        //更新结果
        if($result == 1) {  
            $this->success("更新成功", "admin/index/articles");
        }else {
            $this->success("更新失败"); 
        }
    }
}
